﻿using heyirunde.variable;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Threading;
using System.Web;


namespace heyirunde.variable
{
    public class ImgHelper
    {
        /// <summary>
        /// 构造器
        /// </summary>
        public ImgHelper() { }

        /// <summary>
        /// 保存多张图片，返回图片路径
        /// </summary>
        /// <param name="savePath"></param>
        /// <param name="httpfiles"></param>
        /// <param name="willcompress"></param>
        /// <returns></returns>
        public static string UploadImage(string savePath, HttpFileCollection httpFiles, bool willcompress)
        {
            string pathResult = "";       //要返回的结果
            string commonPath = "/image/" + savePath + "/";         //图片保存的路径

            //如果对应的文件夹不存在，则新建一个文件夹
            if (!Directory.Exists(HttpContext.Current.Server.MapPath(commonPath)))        //如果该方法是静态方法则 Server 前要添加一些东西
            {
                Directory.CreateDirectory(HttpContext.Current.Server.MapPath(commonPath));
            }

            HttpPostedFile file = null;
            string fileName = "";
            string destFile = "";
            string fileNameComPart = DateTime.Now.ToString("yyyyMMddHHmmssffff");

            if (willcompress)
            {
                //压缩
                for (int i = 0; i < httpFiles.Count; i++)
                {
                    //文件名称
                    file = httpFiles[i];        //取一个文件
                    fileName = fileNameComPart + i.ToString() + "." + file.FileName.Split('.')[1].ToLower();

                    if (file == null)
                    {
                        continue;
                    }

                    UploadFileModel model = new UploadFileModel()
                    {
                        file = file,
                        fileName = fileName,
                        savePath = commonPath,
                    };
                    //将工作项加入到线程池队列中，这里可以传递一个线程参数
                    ThreadPool.QueueUserWorkItem(SaveFile, model);
                    Thread.Sleep(100);

                    //将图片转换成 Bitmap 类型，准备压缩图片
                    Bitmap bitmap = (Bitmap)Image.FromStream(file.InputStream);
                    destFile = HttpContext.Current.Server.MapPath(commonPath) + fileNameComPart + i.ToString() + "min." + file.FileName.Split('.')[1].ToLower();
                    Compress(bitmap, destFile, 17);

                    //返回的结果
                    pathResult = pathResult += (commonPath + fileName) + ";";
                }
            }
            else
            {
                //不压缩
                for (int i = 0; i < httpFiles.Count; i++)
                {
                    //文件名称
                    file = httpFiles[i];        //取一个文件
                    if (file == null)
                    {
                        continue;
                    }

                    var contType = file.ContentType.Split('/')[1].ToLower();

                    fileName = fileNameComPart + i.ToString() + "." + contType;

                    UploadFileModel model = new UploadFileModel()
                    {
                        file = file,
                        fileName = fileName,
                        savePath = commonPath,
                    };
                    //将工作项加入到线程池队列中，这里可以传递一个线程参数
                    ThreadPool.QueueUserWorkItem(SaveFile, model);


                    //Thread thread = new Thread(new ThreadStart(TestMethod));

                    // Thread thread = new Thread(new ParameterizedThreadStart(SaveFile));
                    // thread.IsBackground = true;
                    // thread.Start(model);
                    Thread.Sleep(100);



                    //  file.SaveAs(HttpContext.Current.Server.MapPath(commonPath) + fileName);         //图片保存

                    //返回的结果
                    pathResult = pathResult += (model.savePath + model.fileName) + ";";
                }
            }

            return pathResult;

        }


        /// <summary>
        /// 保存file文件
        /// </summary>
        /// <param name="para"></param>
        /// <returns></returns>
        public static void SaveFile(object parameter)
        {
            UploadFileModel para = parameter as UploadFileModel;

            //文件
            HttpPostedFile file = para.file;

            string path = para.savePath;
            string filename = para.fileName;

            var res = System.Web.HttpRuntime.AppDomainAppPath + path + filename;
            // var resultPath = HttpContext.Current.Server.MapPath(path) + filename;
            //保存文件
            file.SaveAs(res);

        }
        public string Uplode(string savepath, HttpPostedFile httpfiles, bool willcompress)
        {
            string pathResult = "";       //要返回的结果
            string commonPath = "/image/" + savepath + "/";         //图片保存的路径

            //如果对应的文件夹不存在，则新建一个文件夹
            if (!Directory.Exists(HttpContext.Current.Server.MapPath(commonPath)))        //如果该方法是静态方法则 Server 前要添加一些东西
            {
                Directory.CreateDirectory(HttpContext.Current.Server.MapPath(commonPath));
            }

            HttpPostedFile file = null;
            string fileName = "";
            string destFile = "";
            string fileNameComPart = DateTime.Now.ToString("yyyyMMddHHmmssffff");

            if (willcompress)
            {

                file = httpfiles;        //取一个文件
                fileName = fileNameComPart + ".png";         //文件名称
                file.SaveAs(HttpContext.Current.Server.MapPath(commonPath) + fileName);         //图片保存

                //将图片转换成 Bitmap 类型，准备压缩图片
                Bitmap bitmap = (Bitmap)Image.FromStream(file.InputStream);
                destFile = HttpContext.Current.Server.MapPath(commonPath) + fileNameComPart + "min.png";
                Compress(bitmap, destFile, 17);

                //返回的结果
                pathResult = commonPath + fileName;

            }
            else
            {

                file = httpfiles;        //取一个文件
                fileName = fileNameComPart + ".png";         //文件名称
                file.SaveAs(HttpContext.Current.Server.MapPath(commonPath) + fileName);         //图片保存

                //返回的结果
                pathResult = commonPath + fileName;

            }
            Thread.Sleep(100);

            return pathResult;
        }



        /// <summary>
        /// 图片压缩(降低质量以减小文件的大小)，保存在某个路径
        /// </summary>
        /// <param name="srcBitMap">传入的Bitmap对象</param>
        /// <param name="destFile">压缩后的图片保存路径</param>
        /// <param name="level">压缩等级，0到100，0 最差质量，100 最佳</param>
        public static void Compress(Bitmap srcBitMap, string destFile, long level)
        {
            Stream s = new FileStream(destFile, FileMode.Create);
            Compress(srcBitMap, s, level);
            s.Close();
        }

        /// <summary>
        /// 图片压缩(降低质量以减小文件的大小)，不用保存到某个路径
        /// </summary>
        /// <param name="srcBitmap">传入的Bitmap对象</param>
        /// <param name="destStream">压缩后的Stream对象</param>
        /// <param name="level">压缩等级，0到100，0 最差质量，100 最佳</param>
        public static void Compress(Bitmap srcBitmap, Stream destStream, long level)
        {
            ImageCodecInfo myImageCodecInfo;
            Encoder myEncoder;
            EncoderParameter myEncoderParameter;
            EncoderParameters myEncoderParameters;

            myImageCodecInfo = GetEncoderInfo("image/jpeg");        //得到一个表示JPEG编码的 imagecodecinfo 对象image/jpeg
            myEncoder = Encoder.Quality;        //根据质量参数类别的全局唯一标识符创建并初始化一个编码器对象

            //创建encoderparameters对象。
            //encoderparameters 对象包含一个encoderparameter对象数组。在本例中，数组中只有一个encoderparameter对象。
            myEncoderParameters = new EncoderParameters(1);

            // Save the bitmap as a JPEG file with 给定的 quality level
            myEncoderParameter = new EncoderParameter(myEncoder, level);
            myEncoderParameters.Param[0] = myEncoderParameter;
            srcBitmap.Save(destStream, myImageCodecInfo, myEncoderParameters);
        }

        /// <summary>
        /// 获取图片编码类型信息：返回 ImageCodecInfo 的 GetEncoderInfo 方法
        /// </summary>
        /// <param name="mimeType">编码类型</param>
        /// <returns></returns>
        private static ImageCodecInfo GetEncoderInfo(String mimeType)
        {
            ImageCodecInfo[] encoders = ImageCodecInfo.GetImageEncoders();

            foreach (ImageCodecInfo ici in encoders)
            {
                if (ici.MimeType.Equals(mimeType))
                    return ici;
            }

            return null;
        }
        /// <summary>
        /// 上传文件model
        /// </summary>
        public class UploadFileModel
        {
            /// <summary>
            /// 保存文件名
            /// </summary>
            public string fileName { get; set; }
            /// <summary>
            /// 保存路径
            /// </summary>
            public string savePath { get; set; }
            /// <summary>
            /// 上传的文件
            /// </summary>
            public HttpPostedFile file { get; set; }
        }

    }
}